package com.nageoffer.shortlink.project.util;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.nageoffer.shortlink.project.common.constant.ShortLinkConstant;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;

import java.util.Date;
import java.util.Optional;

/**
 * 短链接工具类
 */
public class LinkUtil {

    /**
     * 获取短链接有效期时间戳
     * @param validDate
     * @return
     */
    public static long getLinkCacheValidDate(Date validDate){

        return Optional.ofNullable(validDate).map(each-> DateUtil.between(new Date(),each,DateUnit.MS))
                .orElse(ShortLinkConstant.DEFAULT_CREATE_VALID_TIME);

    }

    /**
     * 获取用户真实ip
     * @param request
     * @return
     */
    public static String getRealIp(HttpServletRequest request) {
        if (request == null) {
            return null;
        }

        // 可能存储真实IP的请求头字段（不同代理/负载均衡器可能使用不同字段）
        String[] ipHeaders = {
                "X-Forwarded-For",    // 通用代理转发字段（可能包含多个IP，逗号分隔，第一个为真实IP）
                "Proxy-Client-IP",    // Apache代理字段
                "WL-Proxy-Client-IP", // WebLogic代理字段
                "HTTP_CLIENT_IP",     // 某些代理服务器字段
                "HTTP_X_FORWARDED_FOR" // 某些代理服务器字段
        };

        // 依次从请求头中提取IP
        for (String header : ipHeaders) {
            String ip = request.getHeader(header);
            // 过滤无效值（null、空字符串、"unknown"）
            if (ip != null && ip.length() > 0 && !"unknown".equalsIgnoreCase(ip.trim())) {
                // X-Forwarded-For可能包含多个IP（格式：client, proxy1, proxy2），取第一个
                if (header.equals("X-Forwarded-For")) {
                    int index = ip.indexOf(',');
                    if (index > 0) {
                        ip = ip.substring(0, index).trim();
                    }
                }
                return ip;
            }
        }
        // 如果所有头字段都没有有效IP，直接获取连接的IP（可能是代理服务器IP）
        return request.getRemoteAddr();
    }

        /**
         * 从HTTP请求中解析用户操作系统（适用于Web应用）
         * @param request HTTP请求
         * @return 操作系统名称
         */
        public static String getClientOS(HttpServletRequest request) {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent == null) {
                return "Unknown";
            }
            String userAgentLower = userAgent.toLowerCase();
            if (userAgentLower.contains("windows")) {
                if (userAgentLower.contains("windows nt 10.0")) {
                    return "Windows 10/11";
                } else if (userAgentLower.contains("windows nt 6.3")) {
                    return "Windows 8.1";
                } else if (userAgentLower.contains("windows nt 6.2")) {
                    return "Windows 8";
                } else if (userAgentLower.contains("windows nt 6.1")) {
                    return "Windows 7";
                } else if (userAgentLower.contains("windows nt 6.0")) {
                    return "Windows Vista";
                } else if (userAgentLower.contains("windows nt 5.1")) {
                    return "Windows XP";
                } else {
                    return "Windows";
                }
            } else if (userAgentLower.contains("mac")) {
                return "macOS";
            } else if (userAgentLower.contains("linux")) {
                return "Linux";
            } else if (userAgentLower.contains("android")) {
                return "Android";
            } else if (userAgentLower.contains("iphone") || userAgentLower.contains("ipad")) {
                return "iOS";
            } else if (userAgentLower.contains("x11") || userAgentLower.contains("unix")) {
                return "Unix";
            } else {
                return "Unknown";
            }
        }



        /**
         * 从HTTP请求中解析用户浏览器信息
         * @param request HTTP请求
         * @return 浏览器名称
         */
        public static String getClientBrowser(HttpServletRequest request) {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent == null) {
                return "Unknown";
            }
            String userAgentLower = userAgent.toLowerCase();
            // Chrome 浏览器
            if (userAgentLower.contains("chrome") && !userAgentLower.contains("edg") && !userAgentLower.contains("opr")) {
                return "Chrome";
            }
            // Firefox 浏览器
            else if (userAgentLower.contains("firefox") || userAgentLower.contains("fxios")) {
                return "Firefox";
            }
            // Safari 浏览器
            else if (userAgentLower.contains("safari") && !userAgentLower.contains("chrome")) {
                return "Safari";
            }
            // Edge 浏览器
            else if (userAgentLower.contains("edg") || userAgentLower.contains("edge")) {
                return "Edge";
            }
            // Opera 浏览器
            else if (userAgentLower.contains("opr") || userAgentLower.contains("opera")) {
                return "Opera";
            }
            // IE 浏览器
            else if (userAgentLower.contains("trident") || userAgentLower.contains("msie")) {
                return "Internet Explorer";
            }
            // 微信浏览器
            else if (userAgentLower.contains("micromessenger")) {
                return "WeChat";
            }
            // 手机浏览器
            else if (userAgentLower.contains("mobile")) {
                return "Mobile Browser";
            }
            else {
                return "Unknown";
            }
        }
    /**
     * 获取用户访问设备
     *
     * @param request 请求
     * @return 访问设备
     */
    public static String getDevice(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.toLowerCase().contains("mobile")) {
            return "Mobile";
        }
        return "PC";
    }
    /**
     * 获取用户访问网络
     *
     * @param request 请求
     * @return 访问设备
     */
    public static String getNetwork(HttpServletRequest request) {
        String actualIp = getRealIp(request);
        return actualIp.startsWith("192.168.") || actualIp.startsWith("10.") ? "WIFI" : "Mobile";
    }
    }

